package view;

import XML.XmlFile;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.rmi.RemoteException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioSystem;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.ListCellRenderer;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import controller.ClientController;
import dto.Account;
import dto.Message;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.BoxLayout;
import javax.swing.JLayeredPane;
import java.awt.event.*;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Vector;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import service.*;

public class ChatWindow extends JFrame {

    private static final long serialVersionUID = 1526191208830228799L;
    private JPanel contentPane;
    private JTextPane txtpn;
    private JComboBox<String> font_comboBox;
    private JComboBox<Color> color_comboBox;
    private JComboBox<Integer> size_comboBox;
    private JList member_list;
    private JTextArea sendTextArea;
    private JToggleButton tglbtnB;
    private JToggleButton tglbtnI;
    private Font currentFont;
    private JMenuItem mntmAdd;
    private JButton btnSend;
    private JButton buzzBtn;
    private ChatRoomInt chatRoom;
    private static int windowID;
    private ClientController clientController;
    boolean isAddMemberVisible;
    AddMemberToConv addFrame;
    private XmlFile file_xml = new XmlFile();
    private String windowIdentifier;
    private DefaultListModel model;
    

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    ChatWindow frame = new ChatWindow(null);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ChatWindow(ChatRoomInt chatRoom) {

        windowID++;
        this.chatRoom = chatRoom;
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//        try {
//            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
//        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
//            e.printStackTrace();
//        }
        setBounds(100, 100, 530, 350);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JMenu mnConv = new JMenu("Conversation");
        menuBar.add(mnConv);

        mntmAdd = new JMenuItem("Add to Conversation");
        mntmAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if (!isAddMemberVisible) {
                        isAddMemberVisible = true;
                        System.out.println("Add to conversation is clicked");
                        addFrame = new AddMemberToConv();
                        addFrame.setVisible(true);
                        addFrame.setSize(210, 200);
                        addFrame.setLocationRelativeTo(ChatWindow.this);
                        addFrame.addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosed(WindowEvent ev) {
                                isAddMemberVisible = false;

                            }
                        });
                    }
                } catch (RemoteException ex) {
                    Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
                }


            }
        });
        mnConv.add(mntmAdd);


        final JLayeredPane mainPanel = new JLayeredPane();
        contentPane.add(mainPanel, BorderLayout.CENTER);
        final BoxLayout cardlay = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
        mainPanel.setLayout(cardlay);

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, getWidth(), getHeight());
        mainPanel.add(panel);
        SpringLayout sl_panel = new SpringLayout();
        panel.setLayout(sl_panel);

        JScrollPane scrollPane = new JScrollPane();
        sl_panel.putConstraint(SpringLayout.NORTH, scrollPane, 0, SpringLayout.NORTH, panel);
        sl_panel.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, panel);
        sl_panel.putConstraint(SpringLayout.EAST, scrollPane, -118, SpringLayout.EAST, panel);
        panel.add(scrollPane);

        JButton rmvMember = new JButton("Remove");
        JPanel rmvBtnPanel = new JPanel();
        rmvBtnPanel.add(rmvMember);


        JScrollPane scrollPane_1 = new JScrollPane();
        sl_panel.putConstraint(SpringLayout.NORTH, scrollPane_1, 20, SpringLayout.NORTH, panel);
        sl_panel.putConstraint(SpringLayout.WEST, scrollPane_1, 6, SpringLayout.EAST, scrollPane);
        sl_panel.putConstraint(SpringLayout.EAST, scrollPane_1, -10, SpringLayout.EAST, panel);
        panel.add(scrollPane_1);


        try {
            if (chatRoom != null) {
                model=new DefaultListModel();
                member_list = new JList(model);
                for(Account acc:chatRoom.getChatRoomMembers())
                    model.addElement(acc);
//                member_list.setModel(DefaultListModel);
                member_list.setCellRenderer(new DefaultListCellRenderer() {
                    JLabel lbl = new JLabel();
                    @Override
                    public Component getListCellRendererComponent(JList<?> list, Object value, 
                        int index, boolean isSelected, boolean cellHasFocus) {
                        if(clientController != null && value.equals(clientController.getLoggedInAccount())) {
                            lbl.setText(clientController.getLoggedInAccount().getFirstName() + " (me)");
                            lbl.setFont(new Font(lbl.getFont().getName(), Font.BOLD, lbl.getFont().getSize()));
                        } else {
                            lbl.setText(((Account)value).getFirstName());
                            lbl.setFont(new Font(lbl.getFont().getName(), Font.PLAIN, lbl.getFont().getSize()));
                        }
                        return lbl;
                    }
                    
                });
            }
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
        scrollPane_1.setViewportView(member_list);
        btnSend = new JButton("send");
        sl_panel.putConstraint(SpringLayout.WEST, btnSend, 0, SpringLayout.WEST, scrollPane_1);
        
        btnSend.setIcon(new ImageIcon(ChatWindow.class.getResource("/resources/mail-blue-icon.png")));
        btnSend.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                send();
               
            }
        });
        panel.add(btnSend);
//        panel.add(buzzBtn);
        ///////////////////////send file button//////////////////////////////
        JMenuItem btnSendFile = new JMenuItem("Send File");
        btnSendFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                send_file_name();
            }
        });
        JMenuItem btnSavesession = new JMenuItem("Save Conversation");
        btnSavesession.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // file_xml.WriteAllMessages(file_xml.get_all_messages());  
                file_xml.saveToFile();
                
            }
        });
        mnConv.add(btnSendFile);
        mnConv.add(btnSavesession);
        ///////////////////////////////////////////////////
        final JPanel emotionPanel = new JPanel();
        ((FlowLayout) emotionPanel.getLayout()).setAlignment(FlowLayout.LEFT);
        // emotionPanel.getContentPane().setLayout(new FlowLayout());

        final JButton emotionBtn = new JButton();
        sl_panel.putConstraint(SpringLayout.SOUTH, scrollPane, -1, SpringLayout.NORTH, emotionBtn);
        emotionBtn.setIcon(new ImageIcon(ChatWindow.class.getResource("/resources/oie_hi.gif")));
        sl_panel.putConstraint(SpringLayout.WEST, emotionBtn, 0, SpringLayout.WEST, panel);
        sl_panel.putConstraint(SpringLayout.SOUTH, emotionBtn, -53, SpringLayout.SOUTH, panel);
        emotionBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                emotionPanel.setVisible(!emotionPanel.isVisible());
                if (emotionPanel.isVisible()) {
                    //mainPanel.setLayout(null);
                    emotionPanel.setLocation((int) emotionBtn.getLocation().getX(), (int) emotionBtn.getLocation().getY() - 140);

                } else {
                    mainPanel.setLayout(cardlay);
                }

            }
        });
        panel.add(emotionBtn);

//        List<Path> result = new ArrayList<>();
//        Path dir = Paths.get("../resources/onion/");
//        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
//           for (Path entry : stream) {
//               result.add(entry);
//           }
//       } catch (IOException ex) {
//            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
//        } catch(DirectoryIteratorException ex) {
//           Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
//       }
//        String[] result = null;
//        try {
//            result = new File(getClass().getResource("/resources/onion/").toURI()).list();
//        } catch (URISyntaxException ex) {
//            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        for (Path image : result) {
//            System.out.println(image);
//            JButton lbl = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + image)));
//            lbl.addActionListener(new ActionListener() {
//                @Override
//                public void actionPerformed(ActionEvent e) {
//                    emotionPanel.setVisible(!emotionPanel.isVisible());
//                    send(((JButton) e.getSource()).getIcon());
//
//                }
//            });
//            emotionPanel.add(lbl);
//        }
        ActionListener act = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                emotionPanel.setVisible(!emotionPanel.isVisible());
                send(((JButton) e.getSource()).getIcon());
            }
        };
        
        JButton lbl1 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_003.gif")));
        lbl1.addActionListener(act);
        emotionPanel.add(lbl1);
        
        JButton lbl2 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_016.gif")));
        lbl2.addActionListener(act);
        emotionPanel.add(lbl2);
        
        JButton lbl3 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_019.gif")));
        lbl3.addActionListener(act);
        emotionPanel.add(lbl3);
        
        JButton lbl4 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_054.gif")));
        lbl4.addActionListener(act);
        emotionPanel.add(lbl4);
        
        JButton lbl5 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_065.gif")));
        lbl5.addActionListener(act);
        emotionPanel.add(lbl5);
        
        JButton lbl6 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_076.gif")));
        lbl6.addActionListener(act);
        emotionPanel.add(lbl6);
        
        JButton lbl7 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_123.gif")));
        lbl7.addActionListener(act);
        emotionPanel.add(lbl7);
        
        JButton lbl8 = new JButton(new ImageIcon(ChatWindow.class.getResource("/resources/onion/" + "onion_head_147.gif")));
        lbl8.addActionListener(act);
        emotionPanel.add(lbl8);
        //emotionPanel.setBounds(0, 200, 400 , 200);
        emotionPanel.setVisible(false);
        mainPanel.add(emotionPanel);

        // emotionPanel.pack();
        // emotionPanel.setLocationRelativeTo(this);

        sl_panel.putConstraint(SpringLayout.WEST, emotionBtn, 0, SpringLayout.WEST, panel);
        sl_panel.putConstraint(SpringLayout.SOUTH, emotionBtn, -53, SpringLayout.SOUTH, panel);

        // mainPanel.add(emotionPanel);

        font_comboBox = new JComboBox<>();
        font_comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                setFont();
            }
        });
        sl_panel.putConstraint(SpringLayout.WEST, font_comboBox, 73, SpringLayout.WEST, panel);
        sl_panel.putConstraint(SpringLayout.SOUTH, font_comboBox, -53, SpringLayout.SOUTH, panel);

        font_comboBox.setModel(new DefaultComboBoxModel<>(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()));
        panel.add(font_comboBox);

        color_comboBox = new JComboBox<>();
        sl_panel.putConstraint(SpringLayout.NORTH, btnSend, 6, SpringLayout.SOUTH, color_comboBox);
        sl_panel.putConstraint(SpringLayout.SOUTH, scrollPane_1, -24, SpringLayout.NORTH, color_comboBox);
        color_comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setFont();
            }
        });
        sl_panel.putConstraint(SpringLayout.NORTH, color_comboBox, 0, SpringLayout.NORTH, font_comboBox);
        sl_panel.putConstraint(SpringLayout.WEST, color_comboBox, 6, SpringLayout.EAST, font_comboBox);
        DefaultComboBoxModel<Color> colors = new DefaultComboBoxModel<>(new Color[]{Color.BLACK, Color.GRAY,
                    Color.BLUE, Color.GREEN, Color.MAGENTA, Color.RED, Color.ORANGE, Color.YELLOW});
        color_comboBox.setModel(colors);
        color_comboBox.setRenderer(new ListCellRenderer<Color>() {
            JPanel lbl = new JPanel();

            @Override
            public Component getListCellRendererComponent(JList list,
                    Color value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                lbl.setPreferredSize(new Dimension(20, 18));
                if (isSelected) {
                    lbl.setBackground(value.darker());
                } else {
                    lbl.setBackground(value);
                }
                return lbl;
            }
        });
        panel.add(color_comboBox);

        Integer[] sizes = new Integer[23];
        for (int i = 0; i < sizes.length; i++) {
            sizes[i] = i + 10;
        }
        size_comboBox = new JComboBox(sizes);
        size_comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                setFont();
            }
        });
        sl_panel.putConstraint(SpringLayout.NORTH, size_comboBox, 0, SpringLayout.NORTH, font_comboBox);
        sl_panel.putConstraint(SpringLayout.WEST, size_comboBox, 6, SpringLayout.EAST, color_comboBox);
        size_comboBox.setMaximumRowCount(23);
        panel.add(size_comboBox);

        JLabel lblMembers = new JLabel("Members:");
        sl_panel.putConstraint(SpringLayout.WEST, lblMembers, 6, SpringLayout.EAST, scrollPane);
        sl_panel.putConstraint(SpringLayout.SOUTH, lblMembers, -6, SpringLayout.NORTH, scrollPane_1);

        txtpn = new JTextPane();
        txtpn.setEditable(false);
        scrollPane.setViewportView(txtpn);
        panel.add(lblMembers);

        tglbtnB = new JToggleButton("B");
        tglbtnB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setFont();
            }
        });
        sl_panel.putConstraint(SpringLayout.WEST, tglbtnB, 6, SpringLayout.EAST, size_comboBox);
        sl_panel.putConstraint(SpringLayout.SOUTH, tglbtnB, -53, SpringLayout.SOUTH, panel);
        tglbtnB.setFont(new Font("Tahoma", Font.BOLD, 11));
        panel.add(tglbtnB);

        tglbtnI = new JToggleButton("I");
        buzzBtn=new JButton("Buzz");
        buzzBtn.setOpaque(true);
        buzzBtn.setIcon(new ImageIcon(ChatWindow.class.getResource("/resources/buzzicon.png")));

        buzzBtn.setSize(50,50);
        buzzBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    clientController.getService().sendBuzz(ChatWindow.this.chatRoom);
                    System.out.println(ChatWindow.this.chatRoom.getChatRoomMembers().size());
                } catch (RemoteException ex) {
                    Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        });
        tglbtnI.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setFont();
            }
        });
        sl_panel.putConstraint(SpringLayout.SOUTH, tglbtnI, -53, SpringLayout.SOUTH, panel);
        sl_panel.putConstraint(SpringLayout.SOUTH, buzzBtn, -43, SpringLayout.SOUTH, panel);
        tglbtnI.setFont(new Font("Tahoma", Font.ITALIC, 11));
        sl_panel.putConstraint(SpringLayout.WEST, tglbtnI, 6, SpringLayout.EAST, tglbtnB);
        sl_panel.putConstraint(SpringLayout.WEST, buzzBtn, 5, SpringLayout.EAST, tglbtnI);
        sl_panel.putConstraint(SpringLayout.SOUTH, buzzBtn,-1, SpringLayout.NORTH,btnSend );



        panel.add(tglbtnI);
        panel.add(buzzBtn);
        JScrollPane scrollPane_2 = new JScrollPane();
        sl_panel.putConstraint(SpringLayout.EAST, scrollPane_2, -118, SpringLayout.EAST, panel);
        sl_panel.putConstraint(SpringLayout.NORTH, scrollPane_2, 0, SpringLayout.SOUTH, emotionBtn);
        sl_panel.putConstraint(SpringLayout.WEST, scrollPane_2, 0, SpringLayout.WEST, panel);
        sl_panel.putConstraint(SpringLayout.SOUTH, scrollPane_2, 0, SpringLayout.SOUTH, panel);
        panel.add(scrollPane_2);

        sendTextArea = new JTextArea();
        sl_panel.putConstraint(SpringLayout.WEST, btnSend, 27, SpringLayout.EAST, sendTextArea);


        sendTextArea.setLineWrap(true);
        scrollPane_2.setViewportView(sendTextArea);

        currentFont = UIManager.getDefaults().getFont("TextArea.font");
        font_comboBox.setSelectedItem(currentFont.getName());
        size_comboBox.setSelectedItem(currentFont.getSize());
        this.addWindowListener(new FrameCloseListener());


        StyledDocument doc = (StyledDocument) txtpn.getDocument();
        Style regular = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
        doc.addStyle("regular", regular);

        Style bold = doc.addStyle("bold", regular);
        StyleConstants.setBold(bold, true);

        DefaultCaret caret = (DefaultCaret) txtpn.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    String str=clientController.getService().removeMember(clientController.getLoggedInAccount(),ChatWindow.this.chatRoom);
                    if(str.equals("Abort"))
                        ChatWindow.this.dispose();
                } catch (RemoteException ex) {
                    Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
                    clientController.getChatRooms().remove(ChatWindow.this.chatRoom);
            }
        });
    }

    /**
     * @return the member_list
     */
    public JList getMember_list() {
        return member_list;
    }
   

    /**
     * @param member_list the member_list to set
     */
    public void setMember_list(JList member_list) {
        this.member_list = member_list;
    }

    /**
     * @return the buzzBtn
     */
    public JButton getBuzzBtn() {
        return buzzBtn;
    }

    /**
     * @param buzzBtn the buzzBtn to set
     */
    public void setBuzzBtn(JButton buzzBtn) {
        this.buzzBtn = buzzBtn;
    }

    /**
     * @return the windowIdentifier
     */
    public String getWindowIdentifier() {
        return windowIdentifier;
    }

    /**
     * @param windowIdentifier the windowIdentifier to set
     */
    public void setWindowIdentifier(String windowIdentifier) {
        this.windowIdentifier = windowIdentifier;
    }

    class AddMemberToConv extends JFrame {

        JPanel buttonPanel;
        JPanel contactPanel;
        JPanel mainPanel;
        JList allContacts;
        Vector<Account> contactList;
        JScrollPane mainScrollPane;
        Account memberToAdd;
        int[] selections;
        List<Account> selectedAccounts;
        JButton addButton;
        JButton removeButton;
        DefaultListModel listModel = new DefaultListModel();

        public AddMemberToConv() throws RemoteException {
            buttonPanel = new JPanel();
            mainPanel = new JPanel(new BorderLayout(10, 10));
            contactPanel = new JPanel();
            addButton = new JButton("Add");
            addButton.setSize(140, 140);
            removeButton = new JButton("Remove");
            addButton.setSize(140, 140);

            selectedAccounts = new ArrayList();
            mainScrollPane = new JScrollPane(contactPanel);
            mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            contactList = ClientController.getService().getContactList(clientController.getClientService());
            allContacts = new JList(contactList);
            buttonPanel.add(addButton);
//            buttonPanel.add(removeButton);
            contactPanel.add(allContacts);
            mainPanel.add(mainScrollPane, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.PAGE_START);
            add(mainPanel);
            initListModel();
            ListSelectionListener selectionListener = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) {
                        selectedAccounts = allContacts.getSelectedValuesList();
                        System.out.println("Size of selectedAccounts now=:" + selectedAccounts.size());

                    }
                }
            };
            allContacts.addListSelectionListener(selectionListener);
            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Add button is clicked");

                    addMember();
                }
            });


        }

        public void initListModel() throws RemoteException {
            for (int x = 0; x < ChatWindow.this.chatRoom.getChatRoomMembers().size(); x++) {
                listModel.addElement(ChatWindow.this.chatRoom.getChatRoomMembers().get(x));
            }

        }

        public void addMember() {

            System.out.println("AddMember");
            System.out.println("Number of accounts inside selectedAccounts " + selectedAccounts.size());
            try {
                for (int i = 0; i < selectedAccounts.size(); i++) {
                    memberToAdd = selectedAccounts.get(i);
                    if (!listModel.contains(memberToAdd)) {
//                        listModel.addElement(memberToAdd);
                        chatRoom.addMemberToRoom(memberToAdd);
                        clientController.getService().addToMemberList(memberToAdd, chatRoom);
//                    ChatWindow.this.chatRoom.getChatRoomMembers().add(memberToAdd);

//                        chatRoom.addMemberToRoom(memberToAdd);
                    }
//                    ChatWindow.this.getMember_list().setModel(listModel);
                }
            } catch (RemoteException ex) {
                Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    class FrameCloseListener extends WindowAdapter {

        @Override
        public void windowClosing(WindowEvent e) {
            try {
                clientController.getChatRooms().remove(chatRoom);
                chatRoom.removeMemberFromRoom(clientController.getLoggedInAccount(), ChatWindow.this.chatRoom);
            } catch (RemoteException ex) {
                Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void send_file_name() {
        
            JFileChooser fc = new JFileChooser();
            String filename = null;
            String path = null;

            Message message = new Message();
            message.setBody(filename);
            message.setFrom(clientController.getLoggedInAccount());

            if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                path = fc.getSelectedFile().getPath();
                filename = fc.getSelectedFile().getName();
                File file1 = new File(path);
                FileInputStream Fis;
                try {
                    //Fis = new FileInputStream(file1);
                    byte[] inputFile=readBytesFromFile(file1);
                    
                    ClientController.getService().upload_file(file1.getName(),inputFile, message, this.chatRoom);
                }
                catch (IOException ex) {
                    Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("error in source file");
                
                }
                             
         
            //ClientController.getService().se (message,this.getChatRoom());
        } 
        sendTextArea.setText("");
    }
   private byte[] readBytesFromFile(File file) throws IOException {
      InputStream is = new FileInputStream(file);
      
      // Get the size of the file
      long length = file.length();
  
      // You cannot create an array using a long type.
      // It needs to be an int type.
      // Before converting to an int type, check
      // to ensure that file is not larger than Integer.MAX_VALUE.
      if (length > Integer.MAX_VALUE) {
        throw new IOException("Could not completely read file " + file.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
      }
  
      // Create the byte array to hold the data
      byte[] bytes = new byte[(int)length];
  
      // Read in the bytes
      int offset = 0;
      int numRead = 0;
      while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
          offset += numRead;
      }
  
      // Ensure all the bytes have been read in
      if (offset < bytes.length) {
          throw new IOException("Could not completely read file " + file.getName());
      }
  
      // Close the input stream and return bytes
      is.close();
      return bytes;
  }

    private void send() {
        try {
            if (sendTextArea.getText().equals("")) {
                return;
            }
            Message message = new Message();
            message.setBody(sendTextArea.getText() + "\n");
            message.setColor((Color) color_comboBox.getSelectedItem());
            message.setFont(currentFont);
            message.setDate(new Date());
            message.setFrom(clientController.getLoggedInAccount());
            ClientController.getService().sendMessage(message, this.getChatRoom());
            //  file_xml.set_message(message); 
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        sendTextArea.setText("");
    }
      private void playSound(String soundName) {
        try {
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(getClass().getResource(soundName));
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
        } catch (Exception ex) {
            System.out.println("Error with playing sound.");
            ex.printStackTrace();
        }
    }

    private void send(Icon icon) {
        try {
            Message message = new Message();
            message.setImage((ImageIcon) icon);
            message.setDate(new Date());
            message.setFrom(clientController.getLoggedInAccount());
            ClientController.getService().sendMessage(message, this.getChatRoom());
            //  file_xml.set_message(message);
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void setFont() {
        int style = tglbtnB.isSelected() ? Font.BOLD : 0;
        style += tglbtnI.isSelected() ? Font.ITALIC : 0;
        currentFont = new Font(font_comboBox.getSelectedItem().toString(),
                style, (Integer) size_comboBox.getSelectedItem());
        sendTextArea.setFont(currentFont);
        sendTextArea.setForeground((Color) color_comboBox.getSelectedItem());
    }

    public void appendMessage(Message message) {
        StyledDocument doc = txtpn.getStyledDocument();
        try {
            doc.insertString(doc.getLength(), message.getFrom().getFirstName() + ": ", doc.getStyle("bold"));

            Style style = doc.getStyle("regular");

            DefaultCaret caret = (DefaultCaret) txtpn.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            if (message.getImage() != null) {
                txtpn.setCaretPosition(doc.getLength());
                JLabel jla = new JLabel(message.getImage());
                txtpn.insertComponent(jla);
                doc.insertString(doc.getLength(), "\n", style);
            } else {
                if (message.getFont() != null) {
                    StyleConstants.setFontFamily(style, message.getFont().getFamily());
                    StyleConstants.setFontSize(style, message.getFont().getSize());

                    StyleConstants.setBold(style, message.getFont().getStyle() == Font.BOLD);
                    StyleConstants.setItalic(style, message.getFont().getStyle() == Font.ITALIC);
                    if (message.getFont().getStyle() == Font.BOLD + Font.ITALIC) {
                        StyleConstants.setBold(style, true);
                        StyleConstants.setItalic(style, true);
                    }
                }
                if (message.getColor() != null) {
                    StyleConstants.setForeground(style, message.getColor());
                }
            }
            doc.insertString(doc.getLength(), message.getBody(), style);

        } catch (BadLocationException ex) {
            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

        file_xml.set_message(message);
    }

    public void appendFileMessage(final Message message) {

        StyledDocument doc = txtpn.getStyledDocument();
        try {
            doc.insertString(doc.getLength(), message.getFrom().getFirstName() + ": ", doc.getStyle("bold"));
            Style style = doc.getStyle("regular");
            ///////////////////////////////////////////////////////
            ImageIcon icon = new ImageIcon(getClass().getResource("/resources/down.png"));
            final JLabel lib1 = new JLabel();
            lib1.setIcon(icon);
            lib1.setIconTextGap(3);
            lib1.setText(message.getBody() + "   ");
            lib1.setOpaque(true);
            // lib1.setBackground(new Color(199,200,12));
            lib1.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    lib1.setForeground(Color.blue);
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    lib1.setForeground(Color.cyan);
                }

                ;        
                @Override
           public void mouseClicked(MouseEvent e) {
                    lib1.setForeground(Color.orange);
                    //to download file
                    download_file(message.getBody());
                }

                ;
                @Override
           public void mouseEntered(MouseEvent e) {
                    lib1.setForeground(Color.magenta);
                    lib1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 1,
                            1, 1, Color.pink), "DOWNLOAD", TitledBorder.RIGHT, TitledBorder.BOTTOM));
                    lib1.setCursor(new Cursor(Cursor.HAND_CURSOR));
                }

                ;   
                @Override
           public void mouseExited(MouseEvent e) {
                    lib1.setForeground(Color.black);
                    lib1.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

                }
            ;
            });
            
            ////////////////////////////////////////////////////////
            DefaultCaret caret = (DefaultCaret) txtpn.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

            //doc.insertString(doc.getLength(), message.getBody(), style);
            txtpn.insertComponent(lib1);
            doc.insertString(doc.getLength(), "\n", style);
        } catch (BadLocationException ex) {
            Logger.getLogger(ChatWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void download_file(String file_Name) {
        File fo =new File(file_Name);       

        try {
            byte[] serverFile=ClientController.getService().download_file(file_Name);
            BufferedOutputStream input=new BufferedOutputStream(new FileOutputStream(fo));
            input.write(serverFile);
            input.flush();
            input.close();
            save_file(fo);
        } catch (Exception e) {
            System.out.println("file not found in server side ...");
        }
    }

    public void save_file(File server_file) {

        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Save    ---BIMW CHAT SYS---");
        fc.setName(server_file.getName());
        if (fc.showSaveDialog(fc) == JFileChooser.APPROVE_OPTION) {
            try {
                // fc.setName(server_file.getName());
                File file = new File(fc.getSelectedFile().getAbsolutePath());// fc.getSelectedFile();
                BufferedInputStream input = new BufferedInputStream(new FileInputStream(server_file));
                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));

                int r;
                int numberOfBytesCopied = 0;
                while ((r = input.read()) != -1) {
                    output.write((byte) r);
                    numberOfBytesCopied++;
                }
                input.close();
                output.close();
                JOptionPane.showMessageDialog(null, "file is saved ");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    public void setClientController(ClientController clientController) {
        this.clientController = clientController;
    }

    /**
     * @return the chatRoom
     */
    public ChatRoomInt getChatRoom() {
        return chatRoom;
    }

    public void setChatRoom(ChatRoomInt chatRoom) {
        this.chatRoom = chatRoom;
    }
    

    /**
     * @return the windowID
     */
    public int getWindowID() {
        return windowID;
    }

    /**
     * @param windowID the windowID to set
     */
    public void setWindowID(int windowID) {
        this.windowID = windowID;
    }

    public void disableControls() {
        btnSend.setEnabled(false);
        mntmAdd.setEnabled(false);


    }

    public void terminateYourself() {
        int x = JOptionPane.showConfirmDialog(this, "Sorry, The Connection With The Server Has Been Lost\n "
                + "Would You Like To Save Your Chatting ?", "Server Failure", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (x == JOptionPane.OK_OPTION) {
            file_xml.saveToFile();
        }
        dispose();
    }
    
    public void makeBuzz() {
        playSound("/resources/buzz.wav");

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Point point = getLocationOnScreen();
                for (int i = 0; i < 4; i++) {
                    setLocation(point.x, point.y - 12);
                    setLocation(point.x + 7, point.y);
                    setLocation(point.x, point.y + 12);
                    setLocation(point.x - 7, point.y);
                    try {
                        Thread.sleep(70);
                    } catch (Exception ex) {
                    }
                    setLocation(point.x, point.y);
                }
            }
        });
    
    }
   
}
